<?
function utf8len($str)
{
  $ret = 0;
  $ch = ord($str[0]);
  if($ch & 0x80) {
    if(($ch & 0xe0) == 0xc0) return 2;
    else if(($ch & 0xf0) == 0xe0) return 3;
    else if(($ch & 0xf8) == 0xf0) return 4;
    else return 0;
  }
  else return 1;
}
function utf8strlen($str)
{
  for($len=0,$i=0;$i<strlen($str);$i += utf8len($str[$i])) $len++;
  return $len;
}
function readutf8($str)
{
  $ret = 0;
  if(ord($str[0]) & 0x80) {
    $ch = ord($str[0]);
    if(($ch & 0xe0) == 0xc0) {
      $ret = ($ch & 0x1f) << 6;
      $ret |= (ord($str[1]) & 0x3f);
      return $ret;
    }
    else if(($ch & 0xf0) == 0xe0) {
      $ret = ($ch & 0xf) << 12;
      $ret |= (ord($str[1]) & 0x3f) << 6;
      $ret |= (ord($str[2]) & 0x3f);
      return $ret;
    }
    else if(($ch & 0xf8) == 0xf0) {
      $ret = ($ch & 0x7) << 18;
      $ret |= (ord($str[1]) & 0x3f) << 12;
      $ret |= (ord($str[2]) & 0x3f) << 6;
      $ret |= (ord($str[3]) & 0x3f);
      return $ret;
    }
    else return 0;
  }
  else return ord($str[0]);
}
function js_utf8str($str)
{
  for($buf = '[',$i=0;$i<strlen($str);) {
    $len = utf8len($str[$i]);
    $utf8 = substr($str,$i,$len);
    $buf .= sprintf('0x%x,',readutf8($utf8));
    $i += $len;
  }
  $buf = rtrim($buf,',');
  $buf .= ']';
  return $buf;
}

?>